﻿(function ($) {
    //默认配置
    var settings = {
        tableId: 'mainTable',
        searchId: 'mainSearch',
        cbxId: 'cbxAllMain',
        bDelayLoad: true,
        sUrl: '',
        ajaxData: function (pageIndex, pageSize, orderBy, search) {
            return { pageIndex: pageIndex, pageSize: pageSize, orderBy: orderBy, search: search, rowCount: this.rowCount };
        },
        bFilter: false,
        bLengthChange: true,
        serverSide: true,
        bPaginate: true,
        sScrollX:'90%',
        bServerSide: true,
        scrollX: true,
        bAutoWidth: false,
        aaSorting: [[1, "desc"]],
        oLanguage: {
            "sProcessing": "正在加载中...",
            "sLengthMenu": "页记录数:_MENU_ ",
            "sZeroRecords": "对不起，查询不到相关数据。",
            "sEmptyTable": "暂无数据。",
            "sInfo": "当前：_START_ - _END_ 行，共 _TOTAL_ 行。",
            "sInfoEmpty": "当前：0 行，共 0 行。",
            "sInfoFiltered": "数据表中共为 _MAX_ 条记录",
            "sSearch": "搜索",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        },
        sPaginationType: "full_numbers",
        sDom: '<"page-bottom" rt <"page-bottom-i" lip> ><"clear">',
        sAjaxSource: '',
        aLengthMenu: [10, 15, 20, 50, 100, 200],
        iDisplayLength: 10,
        checkedKeys: [],
        rowCount: 0,
        receiveData: null,        
        fnGetSearchString: function () {
            //构造搜索字符串
            var tableNames = [];
            var columns = [];
            var values = [];
            var operates = [];
            $('#' + this.searchId + ' :input').each(function () {
                var tableName = $(this).attr('tname');
                var column = $(this).attr('cname');
                var value = $(this).val();
                var operate = $(this).attr('operate');
                if (column != '' && value != '') {
                    tableNames.push(tableName);
                    columns.push(column);
                    values.push($.trim(value));
                    operates.push(operate);
                }
            });
            var s = tableNames.join('`') + '|' + columns.join('`') + '|' + values.join('`') + '|' + operates.join('`');
            return s;
        },
        fnGetSortString: function (oSettings, aoData) {
            var sortColumnIndex = oSettings.aaSorting[0][0];
            var sDir = oSettings.aaSorting[0][1];

            for (var i = 0; i < aoData.length; i++) {
                if (aoData[i].name == 'iSortCol_0') {
                    sortColumnIndex = aoData[i].value;
                    sDir = aoData[i + 1].value;
                    break;
                }
            }

            var result = oSettings.aoColumns[sortColumnIndex].mData + " " + sDir;
            return result;
        },
        _fnRowClick: function (fnClick) {
            var _args = this;
            //单击选中
            $('#' + _args.tableId + '>tbody>tr').click(function (e) {
                var bTargetIsCheckbox = e.target.type == 'checkbox';
                var $self = $(this);                                            //tr
                var $check = $self.find('>td>label>input[type=checkbox]:first');      //checkbox
                var b = $check.attr('checked') != 'checked';                    //is checked
                if (bTargetIsCheckbox) b = !b;                                  //target is checkbox
                $check.attr('checked', b);                                      //change uncheck

                if (b) {
                    $self.addClass("success");
                } else {
                    $self.removeClass("success");
                }
                if (fnClick) {
                    var data = $('#' + _args.tableId).dataTable().fnGetData()[$self[0].sectionRowIndex];
                    if (!b) data = null;
                    fnClick(data);
                }
            });
        },
        fnServerData: function (sSource, aoData, fnCallback, oSettings) {
            $.ajax({
                'dataType': 'json',
                'type': 'POST',
                'url': sSource,
                'data': oSettings.oInit.ajaxData(parseInt(aoData[3].value / oSettings._iDisplayLength) + 1, oSettings._iDisplayLength, oSettings.oInit.fnGetSortString(oSettings, aoData), oSettings.oInit.fnGetSearchString()),
                beforeSend: function () {
                    var genTable = $('#' + oSettings.sTableId + '_wrapper');
                    var X = genTable.offset().top;
                    var Y = genTable.offset().left;
                    $("#listOverLayer").css({ height: genTable.height() - 80, top: X, left: Y - 80, width: genTable.width() - 50 }).show();
                },
                error: function (d, t) {
                    $("#listOverLayer").hide();
                    var errorMessage = "脚本错误, 请联系客服人员！";
                    _setErrorInfo(oSettings.sTableId, errorMessage, oSettings.aoColumns.length, fnCallback);
                },
                success: function (data) {
                    if (data.IsSuccess) {
                        oSettings.oInit.receiveData && oSettings.oInit.receiveData(data);
                        fnCallback(data.Data);
                        if (oSettings.oInit.fnRowDbClick) {
                            oSettings.oInit.fnRowDbClick();
                        }
                        if (oSettings.oInit._fnRowClick) {
                            oSettings.oInit._fnRowClick(oSettings.oInit.fnRowClick);
                        }
                        //选中
                        for (var i = 0; i < oSettings.oInit.checkedKeys.length; i++) {
                            $('#' + oSettings.oInit.tableId + ' tbody input[type=checkbox][value=' + oSettings.oInit.checkedKeys[i] + ']').parents('tr').trigger("click");
                        }
                        //总行数赋值                        
                        oSettings.oInit.rowCount = data.Data.iTotalRecords;
                        oSettings.oInit.checkedKeys = [];
                    } else {
                        var errorMessage = "数据读取失败。原因：";
                        if (data.ResponseError.Message == '-1') {
                            errorMessage = "数据延时加载, 可点击搜索载入数据";
                            oSettings.oInit.bDelayLoad = false;
                            oSettings.sAjaxSource = oSettings.oInit.sUrl;
                        } else {
                            if (data.ResponseError.Message.toLowerCase().indexOf("timeout expired") >= 0) {
                                errorMessage += "数据读取超时, 请稍后重试或联系客服人员。";
                            } else {
                                errorMessage += data.ResponseError.Message;
                            }
                        }
                        _setErrorInfo(oSettings.sTableId, errorMessage, oSettings.aoColumns.length, fnCallback);
                    }
                },
                complete: function () {
                    $("#listOverLayer").hide();
                    $('.tip').qtip({
                        content: {
                            text: $(this).html()
                        },
                        position: {
                            target: 'mouse', // Track the mouse as the positioning target
                            adjust: { x: 5, y: 5 } // Offset it slightly from under the mouse
                        }
                    });
                }
            });
        }
    };
    //设置表格错误信息
    var _setErrorInfo = function (id, msg, length, fnCallback) {
        fnCallback({ iTotalRecords: 0, iTotalDisplayRecords: 0, aaData: [] });
        $('#' + id + ' tbody>tr:first').remove();
        $('#' + id).append('<tr><td colspan="' + length + '" class="center">' + msg + '</td></tr>');
    };

    //创建grid
    $.extend($, {
        createGrid: function (args) {
            this.args = $.extend({}, settings, args);
            if (this.args.bDelayLoad) {
                this.args.sUrl = this.args.sAjaxSource;
                this.args.sAjaxSource = '/api/home/DelayLoad';
            }
            this.table = $('#' + this.args.tableId).dataTable(this.args);
            var tableId = this.args.tableId;

            $('#' + this.args.cbxId).on('change', function () {
                var isChecked = this.checked;
                $('#' + tableId + '>tbody>tr>td>label>input[type=checkbox]').each(function (i, e) {
                    this.checked = isChecked;
                });
                if (isChecked) {
                    $('#' + tableId + '>tbody>tr').addClass('success');
                } else {
                    $('#' + tableId + '>tbody>tr.success').removeClass('success');
                }
            });
        }
    });
    $.createGrid.prototype = {
        //选择行数据
        getCheckedRows: function () {
            var checkedRows = [];
            var data = this.table.fnGetData();
            $('#' + this.args.tableId + ' tbody input[type=checkbox]').each(function (i, e) {
                if (this.checked) {
                    checkedRows.push(data[i]);
                }
            });
            return checkedRows;
        },
        //选择行id
        getCheckedIds: function () {
            var checkedIds = [];
            var data = this.table.fnGetData();
            $('#' + this.args.tableId + ' tbody input[type=checkbox]').each(function (i, e) {
                if (this.checked) {
                    checkedIds.push(this.value);
                }
            });
            return checkedIds;
        },
        /* 循环选中行的所有数据 */
        selectedDatas: function () {
            var selectedData = [];

            $(this.table).DataTable().rows().nodes().each(function (e) {
                if ($(e).attr("class").indexOf("success") > -1) {
                    var a = this.row(e).data();
                    selectedData.push(a);
                }

            });
            return selectedData;
        },
        search: function (b) {
            this.table.fnSettings().oInit.rowCount = 0;
            this.table.fnDraw(b);
        },
        del: function (url) {
            var tb = this.table;
            var ids = this.getCheckedIds();
            this.confirmExecute('删除', ids, url);
        },
        confirmExecute: function (executeType, ids, url) {
            if (ids.length < 1) {
                $.msg_box('请选择要' + executeType + '的数据。');
                return false;
            }
            var grid = this;
            var pi = layer.confirm('是否确认要' + executeType + '选中行(' + ids.length + ')？', function (index) {
                layer.close(pi);
                pi = layer.load('执行中...', 120);
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: { ids: ids.join(',') },
                    success: function (data) {
                        if (data.IsSuccess) {
                            if (data.Message && data.Message.length > 0) {
                                layer.alert(data.Message, 1);
                            }else{
                                layer.alert(data.Data, 1);
                            }
                            grid.clickRow(data.CheckedKey);
                            grid.search(true);
                        } else {
                            layer.alert(data.ResponseError.Message);
                        }
                    },
                    complete: function () {
                        layer.close(pi);
                    }
                });
            });
        },
        promptExecute: function (args, url) {
            var pi = layer.prompt(args, function (value) {
                layer.close(pi);
                pi = layer.load('执行中...', 120);
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    success: function (data) {
                        if (data.IsSuccess) {
                            layer.alert(data.Data, 1);
                            grid.clickRow(data.CheckedKey);
                            grid.search(true);
                        } else {
                            layer.alert(data.ResponseError.Message);
                        }
                    },
                    complete: function () {
                        layer.close(pi);
                    }
                });
            });
        },
        add: function (args) {
            var splitChar = args.iframe.src.indexOf('?') > 0 ? '&' : '?';
            args.iframe.src = args.iframe.src + splitChar + 'id=0';
            $.iframe_box(args);
        },
        edit: function (isSingle, args) {               //是否单个编辑 / 弹出框参数
            var ids = this.getCheckedIds();
            if (ids.length < 1) {
                $.msg_box('请选择要操作的数据。', null);
            } else if (ids.length > 1 && isSingle) {
                $.msg_box('只能同时操作一行数据。', null);
            } else {
                var splitChar = args.iframe.src.indexOf('?') > 0 ? '&' : '?';
                args.iframe.src = args.iframe.src + splitChar + 'id=' + ids.join(',');
                $.iframe_box(args);
            }
        },
        editExecute: function (isSingle, fnExecute) {
            var ids = this.getCheckedIds();
            if (ids.length < 1) {
                $.msg_box('请选择要操作的数据。', null);
            } else if (ids.length > 1 && isSingle) {
                $.msg_box('只能同时操作一行数据。', null);
            } else {
                fnExecute();
            }
        },
        print: function (isSingle, url, fnBeforeSubmit) {               //是否打印单个 / 打印页面url
            var ids = this.getCheckedIds();
            if (ids.length < 1) {
                $.msg_box('请选择要打印的数据。', null);
            } else if (ids.length > 1 && isSingle) {
                $.msg_box('只能同时打印一行数据。', null);
            } else {
                if (fnBeforeSubmit) {
                    if (!fnBeforeSubmit()) {
                        return false;
                    }
                }
                var splitChar = url.indexOf('?') > 0 ? '&' : '?';
                url = url + splitChar + 'id=' + ids.join(',');
                window.open(url);
            }
        },
        clickRow: function (id) {
            if (id) {
                var checkedKeys = id.toString().split(',');
                this.table.fnSettings().oInit.checkedKeys = checkedKeys;
            }
        },
        sync: function (executeType, url) {
            var grid = this;
            var pi = layer.confirm('是否确认要' + executeType + '？', function (index) {
            layer.close(pi);
            pi = layer.load('执行中...', 120);
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    if (data.IsSuccess) {
                        if (data.Message && data.Message.length > 0) {
                            layer.alert(data.Message, 1);
                        } else {
                            layer.alert(data.Data, 1);
                        }
                        grid.clickRow(data.CheckedKey);
                        grid.search(true);
                    } else {
                        layer.alert(data.ResponseError.Message);
                    }
                },
                complete: function () {
                    layer.close(pi);
                }
            });
        });
       }
    };
})(jQuery);
